﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using InternshipManagement.Models;

namespace InternshipManagement.Helpers
{
    [Serializable]
    [Flags]
    public enum SiteRoles
    {
        Student = 1 << 0,
        Company = 1 << 1,
        Secretary = 1 << 2,
        Supervisor = 1 << 4
    }

    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        public UserPrivileges Privileges;
        public new SiteRoles Roles;
        private bool FailedRolesAuth = false;
        private AccountRepository accountRepository = new AccountRepository();
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            FailedRolesAuth = false;
            if (httpContext.Session["UserID"] == null)
            {
                return false;
            }
            if (httpContext.Session["Role"] == null)
            {
                FailedRolesAuth = true;
                return false;
            }
            SiteRoles role = (SiteRoles)httpContext.Session["Role"];

            if (Roles != 0 && (Roles & role) != role)
            {
                FailedRolesAuth = true;
                return false;
            }

            if ((int)Privileges != 0 && !((List<int>)httpContext.Session["UserPrivileges"]).Contains((int)Privileges))
            {
                FailedRolesAuth = true;
                return false;
            }

            return true;
        }
        public override void OnAuthorization(AuthorizationContext filterContext)
           {
            base.OnAuthorization(filterContext);
            if (FailedRolesAuth)
            {
                filterContext.Controller.ViewBag.Message = "You are not authorized for this action.";
                filterContext.Result = new ViewResult
                {
                    ViewName = "ShowMessage",
                    ViewData = filterContext.Controller.ViewData
                };
            }
        }
    }

}